package main

import (
	"math/rand"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func main() {
	r := gin.Default()
	//增加日志打印
	addLog(&r)
	//创建Http 请求 Handle，并启动服务
	createHandleAndRun(&r)
}

const keyRequestId = "requestId"

func addLog(r **gin.Engine) {
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}

	(*r).Use(func(context *gin.Context) {
		start := time.Now()
		context.Next()
		logger.Info("incoming request",
			zap.String("path", context.Request.URL.Path),
			zap.Int("status", context.Writer.Status()),
			zap.Duration("elapsed", time.Duration(time.Now().Sub(start).Microseconds())))
	}, func(context *gin.Context) {
		context.Set(keyRequestId, rand.Int())
		context.Next()
	})
}

func createHandleAndRun(r **gin.Engine) {

	(*r).GET("/ping", func(c *gin.Context) {
		h := gin.H{
			"message": "pong",
		}
		if rId, exits := c.Get(keyRequestId); exits {
			h[keyRequestId] = rId
		}

		c.JSON(200, h)
	})

	(*r).GET("/hello", func(c *gin.Context) {
		c.String(200, "Hello")
	})
	(*r).Run(":8081")
}
